package com.imooc.sellspringcloud.server.mq.example;


import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHeaders;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.HashMap;


/**
 * @author
 * @create 2019-08-04 16:50
 **/
@Component
public class TestMQ {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = "testQueue"),
            exchange = @Exchange(value = "testExchange",type = ExchangeTypes.TOPIC),
            key = "testKey"))
    @RabbitHandler
    public void replay(Message message, Channel channel) {
        System.out.println("message:" + message.getPayload());

        Long dec = (Long)message.getHeaders().get(AmqpHeaders.DELIVERY_TAG);
        try {
            channel.basicAck(dec,false);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void send() {
        rabbitTemplate.setConfirmCallback(callback);
        rabbitTemplate.setReturnCallback(returnCallback);
        MessageHeaders headers = new MessageHeaders(new HashMap<>());
        Message<String> message = MessageBuilder.createMessage("hello rabbitmq", headers);
        rabbitTemplate.convertAndSend("testExchange","testKey",message);
    }

    RabbitTemplate.ConfirmCallback callback = new RabbitTemplate.ConfirmCallback() {
        @Override
        public void confirm(CorrelationData correlationData, boolean ack, String cause) {
            System.out.println("CorrelationData: " + correlationData);
            System.out.println("ack: " + ack);
            if(!ack) {
                System.out.println("异常处理机制");
            }
        }
    };

    RabbitTemplate.ReturnCallback returnCallback = new RabbitTemplate.ReturnCallback() {
        @Override
        public void returnedMessage(org.springframework.amqp.core.Message message,
                                    int replyCode, String replyText, String exchange, String routingKey) {
            System.out.println("message pyload: " + message.getBody());
            System.out.println("replyCode: " + replyCode);
            System.out.println("replyText: " + replyText);
            System.out.println("exchange: " + exchange);
            System.out.println("routingKey：" + routingKey);
        }
    };
}